package com.atguigu.yygh.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.atguigu.yygh.oss.prop.OSSProperties;
import com.atguigu.yygh.oss.service.OSSService;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

/**
 * @Author:hx
 * @DateTime:2022/11/14 19:28
 * @Description:
 */
@Service
public class OSSServiceImpl implements OSSService {

    @Autowired
    private OSSProperties ossProperties;

    @Override
    public String upload(MultipartFile file) {

        String fileName = "";

                // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = ossProperties.getEndpoint();
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = ossProperties.getKeyId();
        String accessKeySecret = ossProperties.getKeySecret();
        // 填写Bucket名称，例如examplebucket。
        String bucketName = ossProperties.getBucketName();

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            fileName = new DateTime().toString("yyyy/MM/dd") + "/" + UUID.randomUUID().toString().replace("-","") + file.getOriginalFilename();
            // 创建PutObject请求。
            ossClient.putObject(bucketName, fileName, file.getInputStream());
        } catch (Exception oe) {
            oe.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return "https://"+bucketName+"."+endpoint+"/"+fileName;
    }
}
